package com.ding.service;

import java.sql.ResultSet;

import org.activiti.engine.IdentityService;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.ding.pojo.User;

@Component
public class UserService {
	
	@Autowired
	JdbcTemplate jdbc;
	
	@Autowired
	PasswordEncoder encoder;
	
	@Autowired
	IdentityService identityService;
	
	
	@Transactional
	public boolean save(User user) {
		
		try {
		jdbc.update("INSERT INTO `test`.`users` (`username`, `password`, `enabled`)" + 
				"VALUES" + 
				"  (?, ?, ?) ;"
				,user.getUsername(),user.getPassword(encoder),true
				);
		jdbc.update("INSERT INTO `test`.`authorities` (`username`, `authority`) VALUES(?, ?) ;",user.getUsername(),user.getauthority());
		
		//在Activiti系统中再放入一个用户
		
		jdbc.update("INSERT INTO `test`.`act_id_user` (" + 
				"  `ID_`" + 
				") " + 
				"VALUES" + 
				"  (?) ;"
				,user.getUsername()
				);
		
		//在Activiti系统中放入用户
		org.activiti.engine.identity.User newUser = identityService.newUser(user.getUsername());
		newUser.setPassword(user.getPassword(encoder));
		identityService.saveUser(newUser);
		return true;
		} catch (Exception e) {
			return false;
		}
		
	}
	
	public org.activiti.engine.identity.User findUserByName(String name) {
		org.activiti.engine.identity.User result = null;
		try {
			result = jdbc.queryForObject(
					"select * from `test`.`act_id_user` where ID_ = ?",
					(ResultSet rs, int row)->
					{
					org.activiti.engine.identity.User user = new UserEntity();
							user.setId(String.valueOf(rs.getString("ID_")));
							user.setEmail(String.valueOf(rs.getString("EMAIL_")));
							return user;

					}, name);

		} catch (Exception e) {
		}
		
		return result;
		
	}
	
}
